package org.jeecg.modules.weixi.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.jeecg.common.api.vo.Result;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.weixi.entity.wxUser;
import org.jeecg.modules.weixi.service.wxUserService;
import org.jeecg.modules.weixi.util.EmptyUtil;
import org.jeecg.modules.weixi.util.HttpUtil;
import org.jeecg.modules.weixi.util.WxEnumUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 类名称: LoginController
 * 类描述: TODO
 * 创建人: 帅哥禹品
 * 创建时间 2021/8/9 10:01
 *
 * @Version 1.0
 */
@Api(tags="Login")
@RestController
@RequestMapping("/weixi")
@Slf4j
public class WxLoginController {
    @Resource
    private wxUserService wxUserService;

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public Result login(String code){
        Result<wxUser> result = new Result<wxUser>();
        //把请求参数封装成map
        Map<String,String> param = new HashMap<String,String>();
        param.put("appid", WxEnumUtil.APPID.getName());
        param.put("secret",WxEnumUtil.APPSECRET.getName());
        param.put("js_code",code);
        param.put("grant_type","authorization_code");
        try {
            //写service层
            String results = HttpUtil.get("https://api.weixin.qq.com/sns/jscode2session",param);
            System.out.println(results);
            JSONObject jsonObject = JSON.parseObject(results);
            String openid = jsonObject.getString("openid");
            if(EmptyUtil.isEmptyStr(openid)){
                result.setSuccess(false);
                result.setCode(10001);
                result.setMessage("获取用户openid失败");
            }
            //根据openid去数据库查询，当前Openid在表中是否存在，如果存在则进行登录，
            wxUser user=wxUserService.findOpenId(openid);
            //判断用户信息是否存在
            if(user!=null) {
                //如果用户信息存在
                result.setSuccess(true);
                result.setMessage("用户信息存在");
                result.setResult(wxUserService.findOpenId(openid));
            }else{
                //如果用户信息不存在
                result.setCode(10002);
                result.setSuccess(false);
                result.setMessage("用户信息不存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}

